﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Syndication;
using System.Xml;
using System.IO;

namespace MyPublisher.Emit
{
    public static class EmitExtensions
    {
        public static string ToAtom10(this EmitData data)
        {
            SyndicationItem item =
                new SyndicationItem(data.Title, data.Content, null, Guid.NewGuid().ToString(), DateTime.Now);
            item.Summary = new TextSyndicationContent(data.Content);
            item.Categories.Add(new SyndicationCategory(data.Category));
            item.Copyright = new TextSyndicationContent(data.Copyright);
            foreach (EmitPerson person in data.Authors)
            {
                item.Authors.Add(new SyndicationPerson(person.Email, person.Name, person.Uri));
            }
            item.PublishDate = data.PublishDate;
            item.LastUpdatedTime = DateTime.Today;

            StringBuilder sb = new StringBuilder();
            XmlWriterSettings setting = new XmlWriterSettings(){
                Encoding = Encoding.UTF8
            };
            using (XmlWriter atomWriter = XmlWriter.Create(sb, setting))
            {
                item.SaveAsAtom10(atomWriter);
                atomWriter.Close();
                return sb.Replace("utf-16", "utf-8").ToString();
            }
        }
    }
}
